package hive.jdbc.getEmpInfo.empDao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author:lixinlei
 * @Date:2022-04-15 9:34
 **/
public class EmpMysqlDao {

    public int addEmps(List<Map<String,Object>> emps){

        Connection conn = null;
        PreparedStatement ps = null;

        int addCount = 0;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/hive",
                    "root",
                    "root"
            );

            for (Map<String, Object> emp : emps) {
                try {
                    StringBuffer sb = new StringBuffer();
                    sb.append("insert into emp(");
                    Set<Map.Entry<String, Object>> entries = emp.entrySet();
                    //遍历一次，把要添加的字段补充上，因为顺序不同
                    for (Map.Entry<String, Object> entry : entries) {
                        sb.append(entry.getKey()+",");
                    }

                    sb.append(") values(");
                    //再遍历一次，补充每个字段对应的值
                    for (Map.Entry<String, Object> entry : entries) {
                        sb.append("'"+entry.getValue()+"',");
                    }
                    sb.append(")");
                    String sql = sb.toString();
                    sql = sql.replace(",)",")");
//                            .replace("dept.","")
//                            .replace("emps.","");
                    System.out.println("sqlreplace:"+sql);
                    ps=conn.prepareStatement(sql);

                    int count = ps.executeUpdate();
                    addCount += count;
                }catch (Exception e){
                    continue;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(null!=ps){
                    ps.close();
                }
                if(null!=conn){
                    conn.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return addCount;
    }

}
